package com.example.sourcecodelearning.controller;

import com.example.framework.common.pojo.R;
import com.example.sourcecodelearning.modules.async.AsyncService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

@Tag(name = "长轮询")
@RestController
@RequestMapping("/polling")
public class PollingController {

    @Resource
    private AsyncService asyncService;

    @PermitAll // 长轮询释放 servlet 线程后，当收到变更数据后会重新起一个线程调用，此时没有 authentication 会进入 AuthenticationEntryPoint
    @Operation(summary = "设置监听")
    @GetMapping(path = "watch/{id}")
    public DeferredResult<R<String>> watch(@Parameter(in = ParameterIn.PATH) @PathVariable String id) {
        return asyncService.watch(id);
    }

    @Operation(summary = "变更数据")
    @GetMapping(path = "publish/{id}")
    public R<?> publish(@Parameter(in = ParameterIn.PATH) @PathVariable String id, @RequestParam String message) {
        asyncService.publish(id, message);
        return R.success();
    }

}